package com.zb.nio.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class SocketChannelDemo {
    public static void main(String[] args) throws IOException {
        // 创建SocketChannel
        // 方式一：有参open()
        // SocketChannel sc1 = SocketChannel.open(new InetSocketAddress("www.baidu.com", 80));
        // 方式二：无参open()
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("www.baidu.com", 80));


        socketChannel.configureBlocking(true);

        // 读操作
        ByteBuffer buffer = ByteBuffer.allocate(16);
        socketChannel.read(buffer);
        socketChannel.close();
        System.out.println("read over...");



        // 参数
        // System.out.println("默认发送缓冲区大小："
        //         + sc1.getOption(StandardSocketOptions.SO_SNDBUF));
        // System.out.println("默认接收缓冲区大小："
        //         + sc1.getOption(StandardSocketOptions.SO_RCVBUF));
        // // 默认阻塞模式
        // System.out.println("默认阻塞模式：" + sc1.isBlocking());
        // System.out.println("保活连接："
        //         + sc1.getOption(StandardSocketOptions.SO_KEEPALIVE));
        // System.out.println("禁用 Nagle 算法："
        //         + sc1.getOption(StandardSocketOptions.TCP_NODELAY));
        // System.out.println("--------------");
        // sc1.setOption(StandardSocketOptions.SO_SNDBUF, 4096);
        // System.out.println("发送缓冲区大小："
        //         + sc1.getOption(StandardSocketOptions.SO_SNDBUF));
        // sc1.setOption(StandardSocketOptions.SO_KEEPALIVE, Boolean.TRUE);
        // System.out.println("保活连接："
        //         + sc1.getOption(StandardSocketOptions.SO_KEEPALIVE));
        // System.out.println("--------------");
        // System.out.println("打开：" + sc1.isOpen());
        // System.out.println("连接：" + sc1.isConnected());
        // System.out.println("正在连接：" + sc1.isConnectionPending());
        // System.out.println("完成连接：" + sc1.finishConnect());
        // System.out.println("--------------");
        // // 阻塞模式
        // // 设置阻塞模式
        // sc1.configureBlocking(false);
        // // 读取
        // ByteBuffer buf = ByteBuffer.allocate(24);
        // System.out.println("Reading...");
        // sc1.read(buf);
        // // 关闭
        // sc1.close();
        //
        // System.out.println("--------------");
        // System.out.println("打开：" + sc1.isOpen());
        // System.out.println("连接：" + sc1.isConnected());
        // System.out.println("正在连接：" + sc1.isConnectionPending());
        // // System.out.println("完成连接：" + sc1.finishConnect());
        // System.out.println("--------------");
        // System.out.println("Read Over!");
    }
}
